<template>
    <el-card class="box-card">
       <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

        <!-- 2. 搜索框 -->
    <el-row class="searchRow">
        <el-col :span="16">
            <el-input  clearable @clear="loadUserList()" v-model="query" placeholder="请输入用户名" class="searchInput">
                <el-button @click="searchUser()" slot="append" icon="el-icon-search"></el-button>
            </el-input>
            <el-button type="success" @click="showAddUserDia()">添加用户</el-button>
        </el-col>
    </el-row>
   <!--表格-->
        <el-table :data="userlist" style="width: 100%">
      <el-table-column prop="date" type="index" label="id" > </el-table-column>
      <el-table-column prop="username" label="姓名" > </el-table-column>
      <el-table-column prop="email" label="邮箱" > </el-table-column>
      <el-table-column prop="mobile" label="电话" > </el-table-column>

      <el-table-column label="创建日期">
            <template slot-scope="scope">
                {{scope.row.create_time |fmtdate}}
            </template>
        </el-table-column>

      <el-table-column label="用户状态">
            <template slot-scope="scope">
                <el-switch 
                v-model="scope.row.mg_state" 
                active-color="#13ce66"
                @change="changeUserMgstate(scope.row)" 
                inactive-color="#ff4949">
                </el-switch>
            </template>
        </el-table-column>

      <el-table-column  label="操作" >
          <template slot-scope="scope">
            <el-button size="mini" plain type="primary" icon="el-icon-edit" @click="showEditUserDia(scope.row)" circle></el-button>
            <el-button size="mini" plain type="danger" icon="el-icon-delete" @click="showMegBoxDele(scope.row.id)" circle></el-button>
            <el-button size="mini" plain type="success" @click="showSetRoleDia(scope.row)" icon="el-icon-check" circle></el-button>
          </template>
       </el-table-column>
    </el-table>
    <!--分页-->
       <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[4, 6, 8, 10]"
      :page-size="4"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!--添加用户-->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisibleAdd">
  <el-form :model="form">
    <el-form-item label="用户名" label-width="100px">
      <el-input v-model="form.username" autocomplete="off"></el-input>
    </el-form-item>

    <el-form-item label="密码" label-width="100px">
      <el-input v-model="form.password" autocomplete="off"></el-input>
    </el-form-item>

    <el-form-item label="邮箱" label-width="100px">
      <el-input v-model="form.email" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="电话" label-width="100px">
      <el-input v-model="form.mobile" autocomplete="off"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisibleAdd = false">取 消</el-button>
    <el-button type="primary" @click="addUser()" >确 定</el-button>
  </div>
</el-dialog>

  <!--修改用户-->
    <el-dialog title="修改用户" :visible.sync="dialogFormVisibleEdit">
      <el-form :model="form">
    <el-form-item label="用户名" label-width="100px">
      <el-input v-model="form.username" :disabled="true" autocomplete="off"></el-input>
    </el-form-item>
    
    <el-form-item label="邮箱" label-width="100px">
      <el-input v-model="form.email" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="电话" label-width="100px">
      <el-input v-model="form.mobile" autocomplete="off"></el-input>
    </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisibleEdit = false">取 消</el-button>
    <el-button type="primary" @click="editUser()" >确 定</el-button>
      </div>
    </el-dialog> 

    <!-- 分配角色的对话框 -->

    <el-dialog title="分配角色" :visible.sync="dialogFormVisibleRole">
      <el-form :model="form">
    <el-form-item label="用户名" label-width="100px">
      {{currUsername}}
    </el-form-item>

    <el-form-item label="角色" label-width="100px">
        <el-select v-model="currRoleId">
          <el-option label="请选择" :value="-1"></el-option>
          <el-option
            v-for="(item,i) in roles"
            :key="i"
            :label="item.roleName"
            :value="item.id">
          </el-option>
      </el-select>
    </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisibleRole = false">取 消</el-button>
    <el-button type="primary" @click="setRole()" >确 定</el-button>
      </div>
    </el-dialog> 

    </el-card>
</template>

<script>
 export default{
    data(){
        return{
          query: '',
          userlist: [{
            create_time: '',
            email: '',
            id: '',
            mg_state: '',
            mobile: '',
            role_name: '',
            username: ''
          }],
          // 获取用户数据请求的参数
          pagenum: 1,
          pagesize: 4,
          total: -1,
          dialogFormVisibleAdd: false,
          dialogFormVisibleEdit: false,
          dialogFormVisibleRole:false,
          form: {
            username: '',
            password: '',
            email: '',
            mobile: ''
          },
          // 分配角色
          // 当前用户的用户名
          currUsername: '',
          // 当前用户的角色的id el-select v-model绑定
          currRoleId: -1,
          // 保存角色信息的数据
          roles: [],
          // 当前用户的id
          currUserId: -1
        }
     },
     created() {
        this.getUserList()
     },
    methods:{
     async setRole(){
        const res = await this.$http.put(`users/${this.currUserId}/role`,{
          rid:this.currRoleId
        })
        
        this.dialogFormVisibleRole = false
      },
     async showSetRoleDia(user){
        this.dialogFormVisibleRole= true
        // 给当前的用户id赋值
        this.currUserId = user.id
        this.currUsername = user.username

        const res1 =await this.$http.get('roles')
        this.roles = res1.data.data

        const res2 = await this.$http.get(`users/${user.id}`)
        // console.log(res2)
        this.currRoleId = res2.data.data.rid

      },
      async changeUserMgstate(user){
        const res = await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
      },
      async editUser(){
        this.dialogFormVisibleEdit = false

        const res = await this.$http.put(`users/${this.form.id}`,this.form)
        
        const {meta:{msg,status},data} = res.data
        if(status === 200){
          this.$message.success('更新数据成功')
          this.getUserList();
        }
        
      },
      showEditUserDia(user){
        this.form = user
        this.dialogFormVisibleEdit = true
      },
      showMegBoxDele(userId){
        this.$confirm('是否删除用户?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const res = await this.$http.delete(`users/${userId}`)
          console.log(res);
          //更新视图
          this.getUserList();

          this.$message({
            type: 'success',
            message: res.data.meta.msg
            
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: res.data.meta.msg
          });          
        });
      },
      async addUser(){
        const res = await this.$http.post('/users',this.form)

        this.dialogFormVisibleAdd = false
        //const {meta:{msg,status},data: { total, users }} = res.data
        if(status === 201){
          this.$message.success(msg)
          this.getUserList();
          this.form = {}
        }else{
          this.$message.warning(msg)
        }

      },
      showAddUserDia(){
        this.dialogFormVisibleAdd = true
      },
      loadUserList(){
        this.getUserList()
      },
      searchUser(){
        // 1. 按照query参数发送请求
        this.pagenum = 1
        this.getUserList()
      },
      handleSizeChange(val) {
        this.pagesize = val;
        // 重置页码pagenum
        this.pagenum = 1
        this.getUserList()
      },
      handleCurrentChange(val) {

        this.pagenum = val
        this.getUserList();
      },
      async getUserList(){
        /*const AUTH_TOKEN = localStorage.getItem('token')
        this.$http.defaults.headers.common['Authorization'] = AUTH_TOKEN*/

        const res = await this.$http.get(
        `users?query=${this.query}&pagenum=${this.pagenum}&pagesize=${
          this.pagesize
        }`
      )
        const {
        meta: { msg, status },
        data: { total, users }
      } = res.data
      if (status === 200) {
        // 提示
        // total 和 users
        this.total = total
        this.userlist = users
        this.$message.success(msg)
      } else {
        this.$message.warning(msg)
      }

        }
     }
     
  
 }
</script>

<style>

.box-card {
  height: 100%;
}

.searchRow {
  margin-top: 20px;
}

.searchInput {
  width: 300px;
}

</style>
